//
//  AddFriendViewController.m
//  ChatKit-OC
//
//  Created by th on 2017/3/21.
//  Copyright © 2017年 ElonChan. All rights reserved.
//

#import "AddFriendViewController.h"

@interface AddFriendViewController () <UISearchBarDelegate, UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UISearchBar *searchBar;

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *datas;

@end

@implementation AddFriendViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"添加好友";
    
    _datas = @[].mutableCopy;
    
    [self setupUI];
}


- (void)setupUI {
    
    self.view.backgroundColor = [UIColor colorWithRed:0.91 green:0.93 blue:0.93 alpha:1.00];
    
    _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, kMainWidth, 50)];
    _searchBar.delegate = self;
    _searchBar.placeholder = @"请输入对方名称";
    _searchBar.keyboardType = UIKeyboardTypeDefault;
    
    [self.view addSubview:_searchBar];
    
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 50, kMainWidth, kMainHeight - STATUS_BAR_HEIGHT - NavigationBar_HEIGHT - 50) style:UITableViewStylePlain];
    
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    [self.view addSubview:_tableView];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _datas.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *ID = @"friendCell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }
    
    cell.textLabel.text = ((AVUser *)_datas[indexPath.row]).username;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    //先查询下这个用户是否已经在联系人表中
    
    AVQuery *query = [AVQuery queryWithClassName:kContact];
    
    NSString *username = ((AVUser *)_datas[indexPath.row]).username;
    
    [query whereKey:LCCKProfileKeyName equalTo:username];//精确查询
    
    //    NSString *objectId = ((AVUser *)_datas[indexPath.row]).objectId;
    
    MJWeakSelf;
    [query findObjectsInBackgroundWithBlock:^(NSArray * _Nullable objects, NSError * _Nullable error) {
        
        if (!error) { //查询成功
            if (objects.count > 0) {//当查到数据
                
                AVUser *currentUser = [AVUser currentUser];
                
                if ([currentUser.objectId isEqualToString:[objects[indexPath.row] objectForKey:kowner]]) {
                    [LCCKUtil showNotificationWithTitle:NSStringFormat(@"%@ 已经在您的联系人列表中",username) subtitle:nil type:LCCKMessageNotificationTypeSuccess];
                } else {
                    //这里做添加操作
                    [weakSelf addFriendWithIndex:indexPath.row];
                }
                
            } else { //没有查到数据
                
                [weakSelf addFriendWithIndex:indexPath.row];
            }
        } else {
            [LCCKUtil showNotificationWithTitle:[error localizedDescription] subtitle:nil type:LCCKMessageNotificationTypeError];
        }
    }];
}


- (void)addFriendWithIndex:(NSInteger)index {
    
    AVUser *currentUser = [AVUser currentUser];
    
    void(^queryFriend)() = ^(){
        
        //查询另一个好友是否已经添加了
        
        AVQuery *query = [AVQuery queryWithClassName:kContact];
        
        [query whereKey:LCCKProfileKeyName equalTo:currentUser.username];
        
        [query whereKey:kowner equalTo:((AVUser *)_datas[index]).objectId];
        
        [query findObjectsInBackgroundWithBlock:^(NSArray * _Nullable objects, NSError * _Nullable error) {
            if (!error) {
                
                if (objects.count == 0) {
                    //保存另一个
                    AVObject *oContact = [AVObject objectWithClassName:kContact];
                    
                    [oContact setObject:currentUser.username forKey:LCCKProfileKeyPeerId];
                    [oContact setObject:currentUser.username forKey:LCCKProfileKeyName];
                    
                    NSString *avatarURL = [currentUser objectForKey:kavatarURL];
                    
                    [oContact setObject:avatarURL forKey:LCCKProfileKeyAvatarURL];
                    
                    [oContact setObject:((AVUser *)_datas[index]).objectId forKey:kowner];
                    
                    [oContact saveInBackgroundWithBlock:^(BOOL succeeded, NSError * _Nullable error) {
                        if (!error) {
                            //指定推送给添加的用户
                            NSString *name = ((AVUser *)_datas[index]).username;
                            NSDictionary *data = @{
                                                   @"alert": NSStringFormat(@"%@ 添加您为好友了",name),
                                                   @"objectId": NSStringFormat(@"%@",currentUser.objectId) // Photo's object id
                                                   };
                            
                            AVPush *push = [[AVPush alloc] init];
                            [push setChannel:name];
                            [push setData:data];
//                            [push setMessage:NSStringFormat(@"%@ 添加您为好友了",name)];
                            [push sendPushInBackground];
                        } else {
                            
                        }
                    }];
                }
                
            } else {
                [LCCKUtil showNotificationWithTitle:[error localizedDescription] subtitle:nil type:LCCKMessageNotificationTypeError];
            }
        }];
        
    };
    
    void(^addfriend)() = ^(){
        
        LCCKProfileKeyPeerId;LCCKProfileKeyName;LCCKProfileKeyAvatarURL;
        
        // LeanCloud - 保存对象
        AVObject *contact = [AVObject objectWithClassName:kContact];
        
        [contact setObject:((AVUser *)_datas[index]).username forKey:LCCKProfileKeyPeerId];
        [contact setObject:((AVUser *)_datas[index]).username forKey:LCCKProfileKeyName];
        
        NSString *avatarURL = [((AVUser *)_datas[index]) objectForKey:kavatarURL];
        
        [contact setObject:avatarURL forKey:LCCKProfileKeyAvatarURL];
        
        //owner 字段为 Pointer类型，指向_User表
        //    [contact setObject:currentUser forKey:@"owner"];
        
        [contact setObject:currentUser.objectId forKey:kowner];
        
        [contact saveInBackgroundWithBlock:^(BOOL succeeded, NSError * _Nullable error) {
            if (succeeded) {
                
                queryFriend();
                [LCCKUtil showNotificationWithTitle:@"添加成功" subtitle:nil type:LCCKMessageNotificationTypeSuccess];
                
                [[NSNotificationCenter defaultCenter] postNotificationName:kAddFriendNotification object:nil userInfo:@{kobjectId: contact.objectId}];
                
            } else {
                [LCCKUtil showNotificationWithTitle:[error localizedDescription] subtitle:nil type:LCCKMessageNotificationTypeSuccess];
            }
        }];
    };
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"添加好友" message:((AVUser *)_datas[index]).username preferredStyle:UIAlertControllerStyleAlert];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //点击按钮响应的事件
    }]];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //点击按钮响应的事件
        addfriend();
    }]];
    
    
    [self presentViewController:alert animated:YES completion:nil];
    
}

//开始编辑
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    
    MJWeakSelf;
    
    [UIView animateWithDuration:0.1 animations:^{
        
        [self.navigationController setNavigationBarHidden:YES];
        
        [weakSelf.searchBar setShowsCancelButton:YES];
        
        weakSelf.searchBar.y_pro = STATUS_BAR_HEIGHT;
        
        weakSelf.tableView.y_pro = weakSelf.searchBar.maxY_pro;
        
        weakSelf.tableView.height_pro = kMainHeight - weakSelf.searchBar.maxY_pro;
        
        for (UIView *view in [[_searchBar.subviews lastObject] subviews]) {
            if ([view isKindOfClass:[UIButton class]]) {
                UIButton *cancelBtn = (UIButton *)view;
                [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
            }
        }
    }];
}

//结束编辑
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {
    
    
}

//搜索
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    
    [_searchBar endEditing:YES];
    
    if (_searchBar.text.length > 0) {
        [self saerchWithText:_searchBar.text];
    }
}

- (void)saerchWithText:(NSString *)text {
    
    [self doComplection];
    
    [self.datas removeAllObjects];
    
    //查询 要到后台编辑下 _User权限，要不然查不到的
    AVQuery *query = [AVQuery queryWithClassName:@"_User"];
    [query orderByDescending:@"createdAt"];
    
    //查找username=@"逗比"的数据
    //    [query whereKey:LCCKProfileKeyName equalTo:text];//精确查询
    
    [query whereKey:LCCKProfileKeyName containsString:text];
    
    // owner 为 Pointer，指向 _User 表
    [query includeKey:LCCKProfileKeyName];
    
    MJWeakSelf;
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (!error) {
            
            if (objects.count > 0) {
                
                AVUser *currentUser = [AVUser currentUser];
                
                [objects enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    
                    AVUser *user = objects[idx];
                    
                    if (![user.username isEqualToString:currentUser.username]) {
                        [weakSelf.datas addObject:user];
                    }
                }];
                
                weakSelf.datas = (NSMutableArray *)[[weakSelf.datas reverseObjectEnumerator] allObjects];
                
                [weakSelf.tableView reloadData];
                [LCCKUtil showNotificationWithTitle:NSStringFormat(@"查询成功") subtitle:nil type:LCCKMessageNotificationTypeSuccess];
                
                
            } else {
                [LCCKUtil showNotificationWithTitle:@"没有找到该用户" subtitle:nil type:LCCKMessageNotificationTypeError];
            }
            
        } else {
            [LCCKUtil showNotificationWithTitle:[error localizedDescription] subtitle:nil type:LCCKMessageNotificationTypeError];
        }
    }];
}

//取消
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    
    [self doComplection];
}


- (void)doComplection {
    MJWeakSelf;
    
    _searchBar.text = @"";
    
    [UIView animateWithDuration:0.1 animations:^{
        [self.navigationController setNavigationBarHidden:NO];
        [weakSelf.searchBar setShowsCancelButton:NO];
        [weakSelf.searchBar endEditing:YES];
        
        weakSelf.searchBar.y_pro = 0;
        
        weakSelf.tableView.y_pro = weakSelf.searchBar.maxY_pro;
        
        weakSelf.tableView.height_pro = kMainHeight - STATUS_BAR_HEIGHT - NavigationBar_HEIGHT - 50;
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
